//
//  UserAccount.swift
//  weibo
//
//  Created by lfy on 2018/7/12.
//  Copyright © 2018年 Fly. All rights reserved.
//

import UIKit
import YYModel

private let fileName = "userAccount.json"

/// 用户账户信息
class UserAccount: NSObject {

    /// 访问令牌
    var access_token: String? //= "2.00VUlvCHI4HDAC7d4d8dd38ePs6SdD"
    
    /// 用户ID
    var uid: String? //= "1833008990"
    
    /// 过期日期，单位秒；开发者5年，使用者3天
    var expires_in: TimeInterval = 0 {
        didSet {
            expires_date = Date(timeIntervalSinceNow: expires_in)
        }
    }
    
    /// 过期日期
    var expires_date: Date?
    
    /// 用户昵称
    var screen_name: String?
    
    /// 用户头像地址（大图），180×180像素
    var avatar_large: String?

    override var description: String {
        
        return yy_modelDescription()
        
    }
    
    override init() {
        super.init()
        
        // 1.从磁盘加载保存的账户信息
        let path = fileName.documentAppendingPathComponent()
    
        guard let data = NSData(contentsOfFile: path), let dict = try? JSONSerialization.jsonObject(with: (data as Data), options: []) as? [String: AnyObject] else {
            
            return
            
        }
        
        // 2.使用字典设置属性值
        yy_modelSet(with: (dict ?? [:]))
        
        print("从沙盒加载用户信息 -- \(self)")
        
        // 3.判断token过期
//        expires_date = Date(timeIntervalSinceNow: -3600 * 24 * 365 * 5)// 模拟过期
        if expires_date?.compare(Date()) != .orderedDescending {
            
            print("账户token过期")
            
            // 1.清空token
            access_token = nil
            uid = nil
            
            // 2.删除账户信息文件
            try? FileManager.default.removeItem(atPath: path)
            
        }
        
    }
    
    /// 存储用户信息
    /**
    1.偏好设置（存储小量数据）
    2.沙盒-归档，plist，json
    3.数据库（FMDB/CoreData）
    4.钥匙串（小量数据/自动加密）- 需要框架SSKeyChain
    */
    func saveAccount() {
        
        // 1.模型转字典
        var dict = self.yy_modelToJSONObject() as? [String: Any] ?? [:]
        
        // 2.删除不需要保存到key-value
        dict.removeValue(forKey: "expires_in")
        
        // 3.字典序列化 data
        guard let data = try? JSONSerialization.data(withJSONObject: dict, options: []) else {
            
            return
            
        }

        // 4.写入磁盘
        let path = fileName.documentAppendingPathComponent()
        
        (data as NSData).write(toFile: path, atomically: true)
        
        print("用户信息储存路径 -- \(path)")
        
    }
    
}
